import React, { useState } from 'react';
import { Button, Card, Input, Radio, Tabs, Typography } from 'antd';
import { createStyles } from 'antd-style';
import { CodeOutlined } from '@ant-design/icons';
import MonacoEditor from 'react-monaco-editor';

const { TabPane } = Tabs;
const { TextArea } = Input;

const useStyles = createStyles(({ token }) => ({
  bodyContainer: {
    padding: '16px',
    backgroundColor: token.colorBgContainer,
    borderRadius: token.borderRadius,
    border: `1px solid ${token.colorBorderSecondary}`,
    boxShadow: `0 1px 2px ${token.colorBorderSecondary}`,
    transition: 'all 0.3s',
    '&:hover': {
      boxShadow: `0 3px 6px rgba(0, 0, 0, 0.1)`,
    },
  },
  bodyTitle: {
    marginBottom: '16px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  editorContainer: {
    border: `1px solid ${token.colorBorder}`,
    borderRadius: token.borderRadius,
    overflow: 'hidden',
    marginTop: '16px',
    transition: 'all 0.3s',
    '&:hover': {
      borderColor: token.colorPrimary,
      boxShadow: `0 0 0 2px ${token.colorPrimaryBg}`,
    },
  },
  formatButton: {
    marginTop: '12px',
    transition: 'all 0.3s',
    '&:hover': {
      color: token.colorPrimary,
      backgroundColor: token.colorPrimaryBg,
    },
  },
  radioGroup: {
    '& .ant-radio-button-wrapper': {
      margin: '0 4px',
      borderRadius: '4px',
      transition: 'all 0.3s',
      '&:first-child': {
        marginLeft: 0,
      },
      '&:hover': {
        color: token.colorPrimary,
        borderColor: token.colorPrimary,
      },
    },
    '& .ant-radio-button-wrapper-checked': {
      fontWeight: 'bold',
      '&::before': {
        backgroundColor: token.colorPrimary,
      },
    },
  },
}));

interface RequestBodyProps {
  bodyType: string;
  bodyContent: string;
  onBodyTypeChange: (type: string) => void;
  onBodyContentChange: (content: string) => void;
}

const bodyTypes = [
  { label: 'none', value: 'none' },
  { label: 'form-data', value: 'form-data' },
  { label: 'x-www-form-urlencoded', value: 'x-www-form-urlencoded' },
  { label: 'JSON', value: 'json' },
  { label: 'XML', value: 'xml' },
  { label: 'raw', value: 'raw' },
  { label: 'binary', value: 'binary' },
  { label: 'GraphQL', value: 'graphql' },
];

const RequestBody: React.FC<RequestBodyProps> = ({
  bodyType,
  bodyContent,
  onBodyTypeChange,
  onBodyContentChange,
}) => {
  const { styles } = useStyles();
  const [activeTab, setActiveTab] = useState('body');

  const handleFormatJson = () => {
    try {
      const formatted = JSON.stringify(JSON.parse(bodyContent), null, 2);
      onBodyContentChange(formatted);
    } catch (error) {
      // 处理JSON格式错误
      console.error('JSON格式错误:', error);
    }
  };

  const renderBodyEditor = () => {
    if (bodyType === 'none') {
      return <Typography.Text type="secondary">此请求没有请求体</Typography.Text>;
    }

    if (bodyType === 'json') {
      return (
        <div>
          <div className={styles.editorContainer}>
            <MonacoEditor
              language="json"
              theme="vs"
              value={bodyContent}
              onChange={onBodyContentChange}
              options={{
                minimap: { enabled: false },
                scrollBeyondLastLine: false,
                automaticLayout: true,
                fontSize: 14,
                lineNumbers: 'on',
                scrollbar: {
                  vertical: 'auto',
                  horizontal: 'auto',
                },
              }}
              height="300"
            />
          </div>
          <Button
            type="text"
            icon={<CodeOutlined />}
            onClick={handleFormatJson}
            className={styles.formatButton}
          >
            格式化
          </Button>
        </div>
      );
    }

    // 其他类型的请求体编辑器
    return (
      <TextArea
        value={bodyContent}
        onChange={(e) => onBodyContentChange(e.target.value)}
        placeholder="请输入请求体内容"
        autoSize={{ minRows: 10, maxRows: 20 }}
      />
    );
  };

  return (
    <div className={styles.bodyContainer}>
      <div className={styles.bodyTitle}>
        <Typography.Title level={5}>请求体</Typography.Title>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="Body" key="body">
          <Radio.Group
            options={bodyTypes}
            onChange={(e) => onBodyTypeChange(e.target.value)}
            value={bodyType}
            optionType="button"
            buttonStyle="solid"
          />
          <div style={{ marginTop: '16px' }}>{renderBodyEditor()}</div>
        </TabPane>
        <TabPane tab="预览" key="preview">
          <Card>
            <pre>{bodyContent}</pre>
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default RequestBody;